package eu.boss.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import android.util.Log;
import eu.boss.exceptions.ServerErrorException;

/**
 * This class cares about http requests
 * 
 * @author Arnaud
 * 
 */
public class Http {

	/**
	 * 
	 * @param url
	 * @return PlayerList send by the server
	 */
	public String executeGetRequest(String url, String userHash)
			throws JsonParseException, JsonMappingException,
			IllegalStateException, IOException {

		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		/**
		 * Adding of Accept header,
		 */
		get.addHeader("Accept", "text/plain");
		get.addHeader("Accept-Charset", "utf-8");
		get.addHeader("User-Agent", userHash);

		Log.d("Performing http GET request to url", url);

		HttpResponse response = client.execute(get);
		InputStream is = response.getEntity().getContent();
		String message = convertStreamToString(is);

		Log.d("Response from server", message);

		// ignoring "\n" character
		if (message.substring(message.length() - 1).compareTo("\n") == 0)
			message = message.substring(0, message.length() - 1);

		return message;
	}

	/**
	 * Convert a Stream into a String
	 * 
	 * @param is
	 *            InputStream to convert
	 * @return
	 */
	public String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append((line + "\n"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	/**
	 * 
	 * @param url
	 * @param pairs
	 * @return message response from the server (SUCCESS or FAILED)
	 * @throws ServerErrorException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String executePutRequest(String url, List<NameValuePair> pairs,
			String user) throws ServerErrorException, ClientProtocolException,
			IOException {

		String message = null;
		HttpPut request = new HttpPut(url);
		HttpClient client = new DefaultHttpClient();
		request.addHeader("Accept", "text/plain");
		request.addHeader("Accept-Charset", "utf-8");
		request.addHeader("User-Agent", user);

		Log.d("Performing http PUT request to url", url);
		Log.d("Message to put", pairs.toString());

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
		entity.setContentEncoding(HTTP.UTF_8);
		request.setEntity(entity);
		HttpResponse response = client.execute(request);
		message = convertStreamToString(response.getEntity().getContent());

		if (message.compareTo("SUCCESS") != 0)
			throw new ServerErrorException();
		Log.d("Response from server", message);

		// ignoring "\n" character
		if (message.substring(message.length() - 1).compareTo("\n") == 0)
			message = message.substring(0, message.length() - 1);
		return message;
	}

	/**
	 * 
	 * @param url
	 * @param pairs
	 * @return message response from the server
	 * @throws ServerErrorException
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String executePostRequest(String url, List<NameValuePair> pairs,
			String user) throws ServerErrorException, ClientProtocolException,
			IOException {

		String message = null;
		HttpPost request = new HttpPost(url);
		HttpClient client = new DefaultHttpClient();
		request.addHeader("Accept", "text/plain");
		request.addHeader("Accept-Charset", "utf-8");
		request.addHeader("User-Agent", user);

		Log.d("Performing http PUT request to url", url);
		Log.d("Message to put", pairs.toString());

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
		entity.setContentEncoding(HTTP.UTF_8);
		request.setEntity(entity);
		HttpResponse response = client.execute(request);
		message = convertStreamToString(response.getEntity().getContent());

		Log.d("Response from server", message);
		// ignoring "\n" character
		if (message.substring(message.length() - 1).compareTo("\n") == 0)
			message = message.substring(0, message.length() - 1);

		return message;
	}
}
